
const Koa = require('koa');
const cors = require('koa2-cors');
const koaBody = require('koa-body');
const error = require('koa-json-error');
const path = require('path');

const app = new Koa();

// 获取配置
const config = require('./config');
// 获取路由
const loadRoutes = require('./routes');
// 连接数据库
const db = require('./db');

app
  .use(cors())
  .use(koaBody({
    multipart: true, // 支持上传文件
    // encoding: 'gzip',
    formidable: {
      uploadDir: path.join(__dirname, 'upload/'), // 设置文件上传目录
      keepExtensions: true,    // 保持文件的后缀
      maxFieldsSize: 20 * 1024 * 1024, // 文件上传大小
    }
  }))
  // .use(bodyParser)
  .use(error({
    postFormat: (e, { stack, ...rest }) => process.env.NODE_ENV === 'production' ? rest : { stack, ...rest }
  }));

// 加载路由模块
loadRoutes(app);

app.listen(config.PORT, () => {
  console.log(`listen: http://localhost:${config.PORT}/`)
  db
    .sequelize
    .sync({ force: false })
    .then(res => {
      console.log('success>>>')
    })
    .catch(err => {
      console.error('error>>>', err)
    })
})